import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:jm_flutter/jm_flutter.dart';
import 'package:jm_usb/jm_usb.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final tag = "HomePage";
  List<UsbDevice> deviceList = [];
  bool connected = false;
  String data = "";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    JmUsb.init();
    JmUsb.connectStream.listen((event) {
      logd(tag, "Connect Stream: $event");
    });

    JmUsb.dataReceivedStream.listen((event) {
      logd(tag, "Data Received: $event");
      setState(() {
        data += event.toString();
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Jm USB Plugin example'),
      ),
      body: ListView(
        shrinkWrap: true,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              OutlinedButton(
                  onPressed: () {
                    JmUsb.getDeviceList().then((value) {
                      logd(tag, "Device List: $value");
                      setState(() {
                        deviceList = value;
                      });
                    });
                  },
                  child: const Text('Get Devices')),
              OutlinedButton(
                  onPressed: () {
                    JmUsb.quickConnectDevice(deviceList.first).then((value) {
                      logd(tag, "quickConnectDevice: $value");
                      if (value) {
                        JmUsb.startDataListening();
                        logd(tag, "Start Data Listening");
                      }
                      setState(() {
                        connected = value;
                      });
                    });
                  },
                  child: const Text('Quick Connect Device')),
            ],
          ),
          ListView.builder(
            shrinkWrap: true,
            itemCount: deviceList.length,
            itemBuilder: (BuildContext context, int index) {
              final device = deviceList[index];

              return ListTile(
                  title: Text(device.deviceName),
                  subtitle: Text(device.toString()),
                  trailing: OutlinedButton(
                    onPressed: () async {
                      final permissionRes =
                          await JmUsb.requestPermission(device);
                      if (!permissionRes) {
                        logd(tag, "Permission denied");
                        return;
                      }

                      final openRes = await JmUsb.openDevice(device);
                      logd(tag, "Open result: $openRes");
                    },
                    child: const Text('open'),
                  ));
            },
          ),
          const Divider(),
          Visibility(
            visible: connected,
            child: Column(
              children: [
                Row(
                  children: [
                    OutlinedButton(
                      onPressed: () {
                        JmUsb.writeData(Uint8List.fromList([0x01, 0x02, 0x03]))
                            .then((value) {
                          logd(tag, "Write Data: $value");
                        });
                      },
                      child: const Text('Write Data(1,2,3)'),
                    ),
                    Text(data),
                  ],
                )
              ],
            ),
          ),
          SizedBox(height: 200, child: LogWidget()),
        ],
      ),
    );
  }
}
